package [package].config;


import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.binding.MapperMethod;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Signature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * mybatis拦截器，自动注入创建人、创建时间、修改人、修改时间
 */
@Slf4j
@Component
@Intercepts({@Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class})})
public class MybatisInterceptor implements Interceptor {

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        MappedStatement mappedStatement = (MappedStatement) invocation.getArgs()[0];
        String sqlId = mappedStatement.getId();
        log.debug("------sqlId------" + sqlId);
        SqlCommandType sqlCommandType = mappedStatement.getSqlCommandType();
        Object parameter = invocation.getArgs()[1];
        log.debug("------sqlCommandType------" + sqlCommandType);

        if (parameter == null) {
            return invocation.proceed();
        }


        //如果是INSERT操作
        if (SqlCommandType.INSERT == sqlCommandType) {

            //拿到所有字段
            Field[] fields = getFields(parameter);

            for (Field field : fields) {
                log.debug("------field.name------" + field.getName());
                try {
                    // 注入创建时间
                    if ("created".equals(field.getName())) {
                        field.setAccessible(true);
                        Object local_created = field.get(parameter);
                        field.setAccessible(false);
                        if (local_created == null || local_created.equals("")) {
                            field.setAccessible(true);
                            field.set(parameter, LocalDateTime.now());
                            field.setAccessible(false);
                        }
                    }
                } catch (Exception e) {
                }
            }
        }

        //如果是UPDATE操作
        if (SqlCommandType.UPDATE == sqlCommandType) {

            if (parameter instanceof MapperMethod.ParamMap) {
                MapperMethod.ParamMap<?> p = (MapperMethod.ParamMap<?>) parameter;

                if (p.containsKey("et")) {
                    parameter = p.get("et");
                } else {
                    parameter = p.get("param1");
                }

                if (parameter == null) {
                    return invocation.proceed();
                }

            }

            Field[] fields = getFields(parameter);

            for (Field field : fields) {
                log.debug("------field.name------" + field.getName());
                try {
                    if ("updated".equals(field.getName())) {
                        field.setAccessible(true);
                        field.set(parameter, LocalDateTime.now());
                        field.setAccessible(false);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return invocation.proceed();
    }


    /**
     * 获取所有字段
     *
     * @param parameter
     * @return
     */
    private Field[] getFields(Object parameter) {
        List<Field> fieldList = new ArrayList<>();
        Class<?> clazz = parameter.getClass();
        while (clazz != null) {
            fieldList.addAll(new ArrayList<>(Arrays.asList(clazz.getDeclaredFields())));
            clazz = clazz.getSuperclass();
        }
        Field[] fields = new Field[fieldList.size()];
        fieldList.toArray(fields);
        return fields;
    }
}
